/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-05 14:23:07
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-12 13:50:19
 * @FilePath: /operator-manager/src/pages/FindPw/components/PhoneCode/PhoneCode.tsx
 * @Description: 找回密码-手机号验证
 */

import { ProFormCaptcha, ProFormText } from '@ant-design/pro-components';
import { Form, message } from 'antd';
// import { useImperativeHandle,forwardRef,useState } from 'react';
import { phoneForSend, phoneIsValid } from '@/services';
import { accountType } from '@/utils/globalConstants';
import { phoneReg } from '@/utils/validate';
import { forwardRef, useImperativeHandle } from 'react';
import { FindForm } from '../../type.d';

const PhoneCode: React.ForwardRefRenderFunction<
  unknown,
  Record<string, any>
> = (_, ref) => {
  const [form] = Form.useForm();
  // const [phoneError,setPhoneError]=useState(true)
  useImperativeHandle(
    ref,
    () => {
      return {
        phoneCodeForm: form,
      };
    },
    [form],
  );
  return (
    <Form
      style={{ width: '100%' }}
      form={form}
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 19 }}
    >
      <ProFormText
        fieldProps={{
          size: 'large',
        }}
        label="手机号"
        name={FindForm.PHONE}
        placeholder={'请输入注册手机号'}
        // validateTrigger="onBlur"
        // rules={[
        //   {validator:async(_,value)=>{
        //     if(value){
        //       const result = await phoneIsValid({data:{[FindForm.PHONE]:value}});
        //       if(result){
        //         setPhoneError(false)
        //         return Promise.resolve()
        //       }
        //     }
        //     setPhoneError(true)
        //     return Promise.reject('请输入注册的手机号')
        //   }}
        // ]}
        rules={[
          { required: true, message: '请输入手机号' },
          { pattern: phoneReg, message: '请输入正确格式的手机号' },
        ]}
      />
      <ProFormCaptcha
        fieldProps={{
          size: 'large',
        }}
        captchaProps={{
          size: 'large',
        }}
        placeholder={'请输入验证码'}
        captchaTextRender={(timing, count) => {
          if (timing) {
            return `${count}后再次获取`;
          }
          return '获取验证码';
        }}
        label="验证码"
        phoneName={FindForm.PHONE}
        name={FindForm.CODE}
        rules={[{ required: true, message: '请输入验证码' }]}
        onGetCaptcha={async (phone) => {
          const res = await phoneIsValid({
            data: { mobile: phone, type: accountType },
          }); // 验证手机号是否已注册
          if (res) {
            const result = await phoneForSend({ params: { mobile: phone } });
            if (result?.success) {
              message.success('获取验证码成功');
            } else {
              throw new Error('获取验证码失败,请重新获取');
            }
          } else {
            throw new Error();
          }
        }}
      />
    </Form>
  );
};

export default forwardRef(PhoneCode);
